package com.cqie.teacherserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqie.teacherserver.entity.*;
import com.cqie.teacherserver.entity.vo.CapacityTagVO;
import com.cqie.teacherserver.entity.vo.TechnicalNumberVO;
import com.cqie.teacherserver.enums.CapacityTag;
import com.cqie.teacherserver.mapper.ScientificPapersInfoMapper;
import com.cqie.teacherserver.mapper.TeacherBaseInfoMapper;
import com.cqie.teacherserver.mapper.TeacherEducationReformInfoMapper;
import com.cqie.teacherserver.mapper.TeacherTeachingStatisticsMapper;
import com.cqie.teacherserver.service.ITeacherEducationReformInfoService;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 教师教改信息 服务实现类
 * </p>
 *
 * @author zhangr132
 * @since 2024-05-31
 */
@Service
public class TeacherEducationReformInfoServiceImpl extends ServiceImpl<TeacherEducationReformInfoMapper, TeacherEducationReformInfo> implements ITeacherEducationReformInfoService {
    @Autowired
    private ScientificPapersInfoMapper scientificPapersInfoMapper;

    @Autowired
    private TeacherBaseInfoMapper teacherBaseInfoMapper;

    @Autowired
    private TeacherTeachingStatisticsMapper teacherTeachingStatisticsMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public R getTeacherTechnicalMsg(Serializable gh) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        CompletableFuture<Integer> educationCompletableFuture = CompletableFuture.supplyAsync(() ->
                        count(new LambdaQueryWrapper<TeacherEducationReformInfo>().eq(TeacherEducationReformInfo::getTdrygh, gh))
                , executorService);
        CompletableFuture<Integer> scientificCompletableFuture = CompletableFuture.supplyAsync(() ->
                        scientificPapersInfoMapper.selectCount(new LambdaQueryWrapper<ScientificPapersInfo>().eq(ScientificPapersInfo::getDyzzgh, gh))
                , executorService);
        CompletableFuture.allOf(educationCompletableFuture, scientificCompletableFuture);
        return R.ok(new TechnicalNumberVO(scientificCompletableFuture.join(), educationCompletableFuture.join()));
    }

    @Override
    public R getCapacityTagByTeacher(Serializable gh) {
        try {
            StringBuffer tags = new StringBuffer();
            ExecutorService executorService = Executors.newCachedThreadPool();
//        获取基本信息
            CompletableFuture<TeacherBaseInfo> teacherBaseInfoCompletableFuture = CompletableFuture.supplyAsync(() ->
                            teacherBaseInfoMapper.selectOne(new LambdaQueryWrapper<TeacherBaseInfo>().eq(TeacherBaseInfo::getGh, gh))
                    , executorService);
            CompletableFuture<Integer> scientificCompletableFuture = CompletableFuture.supplyAsync(() ->
                            scientificPapersInfoMapper.selectCount(new LambdaQueryWrapper<ScientificPapersInfo>().eq(ScientificPapersInfo::getDyzzgh, gh))
                    , executorService);
            CompletableFuture<Integer> TeachingCompletableFuture = CompletableFuture.supplyAsync(() ->
                            teacherTeachingStatisticsMapper.selectCount(new LambdaQueryWrapper<TeacherTeachingStatistics>().eq(TeacherTeachingStatistics::getXgh, gh))
                    , executorService);
            CompletableFuture.allOf(teacherBaseInfoCompletableFuture, scientificCompletableFuture, TeachingCompletableFuture);
            CapacityTagVO capacityTagVO = new CapacityTagVO();
            TeacherBaseInfo teacherBaseInfo = teacherBaseInfoCompletableFuture.join();
            Integer courseNum = TeachingCompletableFuture.join();
            Integer scientificResearch = scientificCompletableFuture.join();
            capacityTagVO.setName(teacherBaseInfo.getXm());
            if (teacherBaseInfo.getXm().equals("教授") || teacherBaseInfo.getGw().equals("副教授")) {
                capacityTagVO.setPosition("教授");
            } else {
                capacityTagVO.setPosition("讲师");
            }
            if (courseNum >= 2) {
                tags.append(CapacityTag.EXCELLENT_TEACHING_PROFESSIONAL.getDescription());
            }
            if (scientificResearch > 2) {
                tags.append(CapacityTag.OUTSTANDING_SCIENTIFIC_RESEARCHER.getDescription());
            }
            if (tags.length() == 0) {
                tags.append(CapacityTag.INTIMATE_GOOD_TEACHER.getDescription());
            }
            capacityTagVO.setTag(tags);
            TeacherReportIndex teacherReportIndex = new TeacherReportIndex();
            teacherReportIndex.setAbilityTag(String.valueOf(tags))
                              .setName(teacherBaseInfo.getXm())
                              .setCoursesAmount(String.valueOf(courseNum))
                              .setDepartment(teacherBaseInfo.getSzdwbm())
                              .setTeacherCode((String) gh)
                              .setProfessionalTitle(capacityTagVO.getPosition())
                              .setHireDate(teacherBaseInfo.getLxrq())
                              .setWorkingDays(calculateDuration(teacherBaseInfo.getLxrq()))
                              .setResearchProjectsAmount(String.valueOf(scientificResearch));
            rabbitTemplate.convertAndSend("teacher_report",teacherReportIndex);
            return R.ok(capacityTagVO);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn(e.getMessage());
        }
        return R.failed("获取失败");
    }

    public static String calculateDuration(String dbTime) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date pastDate = format.parse(dbTime);
        Date currentDate = new Date();
        // 计算时间差（以毫秒为单位）
        long durationMillis = currentDate.getTime() - pastDate.getTime();
        long days = durationMillis / (1000 * 60 * 60 * 24);
        long hours = (durationMillis % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        long minutes = (durationMillis % (1000 * 60 * 60)) / (1000 * 60);
        long seconds = (durationMillis % (1000 * 60)) / 1000;
        return (days + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒");
    }
}